<template>
  <div class="stepList">
    <el-steps class="steps" :active="step" finish-status="success">
      <el-step title="商品基本信息" />
      <el-step title="添加库存信息" />
      <el-step title="添加移动端详情" />
    </el-steps>
    <el-card shadow="never" class="margin_30">
      <!-- card body -->
      <el-form :model="form" label-width="110px" size="small">
        <!-- 第一步 -->
        <div v-show="step==1">
          <p>基本信息</p>
          <el-divider />
          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="商品名称" prop="name">
                <el-input v-model="form.product.name" style="width:80%" />
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item label="商品编码">
                <el-input v-model="form.product.productSn" style="width:80%" />
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item label="商品分类">
                <el-select v-model="form.product.productCategoryId" style="width:80%" size="small" placeholder="商品分类" clearable filterable @change="getCategoryName">
                  <el-option
                    v-for="item in categoryList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="商品品牌">
                <el-select v-model="form.product.brandId" style="width:80%" size="small" value-key="" placeholder="品牌" clearable filterable @change="getBrandName">
                  <el-option
                    v-for="item in brandList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="15" :offset="0">
              <el-form-item label="商品描述">
                <el-input v-model="form.product.description" placeholder="商品描述" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
          <p>商品属性</p>
          <el-divider />
          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="商品原价">
                <el-input-number v-model="form.product.originalPrice" style="width:80%" placeholder="0" :step="1" />
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <!-- promotionType (integer, optional): 促销类型：0->没有促销使用原价;1->使用促销价；2->使用会员价；3->使用阶梯价格；4->使用满减价格；5->限时购 -->
              <el-form-item label="促销类型">
                <el-select v-model="form.product.promotionType" style="width:80%" disabled placeholder="没有促销使用原价">
                  <el-option label="没有促销使用原价" :value="0" />
                  <el-option label="使用促销价" :value="1" />
                  <el-option label="使用会员价" :value="2" />
                  <el-option label="使用阶梯价格" :value="3" />
                  <el-option label="使用满减价格" :value="4" />
                  <el-option label="限时购" :value="5" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item label="活动价格">
                <el-input-number v-model="form.product.promotionPrice" style="width:80%" placeholder="0" :disabled="true" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="重量(kg)">
                <el-input-number v-model="form.product.weight" style="width:80%" :step="1" placeholder="0" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <!-- verifyStatus (integer, optional): 审核状态：0->未审核；1->审核通过 , -->
              <el-form-item label="审核状态">
                <el-switch v-model="form.product.verifyStatus" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <!-- publishStatus (integer, optional): 上架状态：0->下架；1->上架 , -->
              <el-form-item label="是否上架">
                <el-switch v-model="form.product.publishStatus" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <!-- verifyStatus (integer, optional): 审核状态：0->未审核；1->审核通过 , -->
              <el-form-item label="缩略图">
                <el-upload
                  ref="clearUpload"
                  class="avatar-uploader"
                  :action="uploadFileOss"
                  :headers="token"
                  :show-file-list="false"
                  :on-success="coverImgUploadSucc"
                  :before-upload="beforeCoverImgUpload"
                >
                  <img v-if="form.product.pic" :src="form.product.pic" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <p>其他信息</p>
          <el-divider />
          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <!-- recommendStatus (integer, optional): 推荐状态；0->不推荐；1->推荐 , -->
              <el-form-item label="推荐状态">
                <el-switch v-model="form.product.recommendStatus" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <!-- newStatus (integer, optional): 新品状态:0->不是新品；1->新品 , -->
              <el-form-item label="新品状态">
                <el-switch v-model="form.product.newStatus" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <!-- previewStatus (integer, optional): 是否为预告商品：0->不是；1->是 , -->
              <el-form-item label="预告商品">
                <el-switch v-model="form.product.previewStatus" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="搜索关键词">
                <el-input v-model="form.product.keywords" style="width:80%" placeholder="关键词" />
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item label="库存预警">
                <el-input-number v-model="form.product.lowStock" style="width:80%" :step="1" />
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item label="商品排序">
                <el-input-number v-model="form.product.sort" style="width:80%" :step="1" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-form-item label="产品服务">
                <!-- serviceIds (string, optional): 以逗号分割的产品服务：1->无忧退货；2->快速退款；3->免费包邮 , -->
                <el-checkbox-group v-model="form.product.serviceIds">
                  <el-checkbox label="1">无忧退货</el-checkbox>
                  <el-checkbox label="2">快速退款</el-checkbox>
                  <el-checkbox label="3">免费包邮</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0" />
          </el-row>

        </div>
        <!-- 第二步 -->
        <div v-show="step==2">
          <p>商品sku信息</p>
          <el-divider />
          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="标题">
                <el-input v-model="form.product.detailTitle" style="width:80%" />
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="副标题">
                <el-input v-model="form.product.subTitle" style="width:80%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24" :offset="0">

              <el-form-item label="画册图片">
                <el-upload
                  :file-list="fileList"
                  :headers="token"
                  :action="uploadFileOss"
                  list-type="picture-card"
                  :limit="5"
                  :on-success="uptAlbumPics"
                  :before-upload="beforeCoverImgUpload"
                >
                  <i slot="default" class="el-icon-plus" />
                  <div slot="file" slot-scope="{file}">
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url"
                      alt=""
                    >
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)"
                      >
                        <i class="el-icon-zoom-in" />
                      </span>
                      <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handleDownload(file)"
                      >
                        <i class="el-icon-download" />
                      </span>
                      <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handleRemove(file, fileList)"
                      >
                        <i class="el-icon-delete" />
                      </span>
                    </span>
                  </div>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb,文件不超过5个</div>
                </el-upload>
              </el-form-item>

              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-form-item label="sku设置">
              <el-row v-if="colorList.length>0" :gutter="20">
                <el-col :span="12" :offset="0" style="padding-left:0px">
                  颜色:
                  <span v-for="(item,index) in colorList" :key="item.name">
                    <el-checkbox v-model="item.isSelected" :label="item.name" :indeterminate="false" />
                    <el-link style="padding:0 10px" type="danger" :underline="false" @click="delColor(index)">删除</el-link>
                  </span>
                </el-col>
              </el-row>
              <el-row v-if="sizeList.length>0" :gutter="20">
                <el-col :span="12" :offset="0">
                  大小:
                  <span v-for="(item,index) in sizeList" :key="item.name">
                    <el-checkbox v-model="item.isSelected" :label="item.name" :indeterminate="false" />
                    <el-link style="padding:0 10px" type="danger" :underline="false" @click="delSize(index)">删除</el-link>
                  </span>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="4" :offset="0">
                  <el-input v-model.trim="color" placeholder="颜色描述" clearable />
                </el-col>
                <el-col :span="2" :offset="0">
                  <el-button size="small" @click="addColor">创建颜色选项</el-button>
                </el-col>
                <el-col :span="4" :offset="1">
                  <el-input v-model.trim="size" placeholder="大小" clearable />
                </el-col>
                <el-col :span="2" :offset="0">
                  <el-button size="small" @click="addSize">创建大小选项</el-button>
                </el-col>
                <el-col :span="6" :offset="4">
                  <el-button type="primary" size="small" @click="sku">生成sku列表</el-button>
                  <el-button type="primary" size="small" @click="addSku">新增sku</el-button>
                </el-col>
              </el-row>
              <el-table v-if="form.pmsSkuStockList.length>0" :data="form.pmsSkuStockList" border stripe>
                <el-table-column
                  prop="#"
                  type="index"
                  label="序号"
                />
                <el-table-column
                  prop="id"
                  label="图片"
                >
                  <template v-slot="scope">
                    <el-upload
                      class="avatar-uploader"
                      :headers="token"
                      :action="uploadFileOss"
                      :show-file-list="false"
                      :on-success="ele=>getUploadImg(ele.data.fileUrl,scope.$index)"
                    >
                      <img v-if="scope.row.pic" style="width:100px;height:100px" :src="scope.row.pic" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon" />
                    </el-upload>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="id"
                  label="颜色"
                >
                  <template v-slot="scope">
                    <el-input v-model="scope.row.spData[0].value" placeholder="" size="normal" clearable />
                  </template>
                </el-table-column>
                <el-table-column
                  prop="id"
                  label="大小"
                >
                  <template v-slot="scope">
                    <el-input v-model="scope.row.spData[1].value" placeholder="" size="normal" clearable />
                  </template>
                </el-table-column>
                <el-table-column
                  prop="id"
                  label="库存"
                >
                  <template v-slot="scope">
                    <el-input v-model="scope.row.stock" placeholder="" size="normal" clearable />
                  </template>
                </el-table-column>
                <el-table-column
                  prop="id"
                  label="预警库存"
                >
                  <template v-slot="scope">
                    <el-input v-model="scope.row.lockStock" placeholder="" size="normal" clearable />
                  </template>
                </el-table-column>
                <el-table-column
                  prop="id"
                  label="锁定库存"
                >
                  <template v-slot="scope">
                    <el-input v-model="scope.row.lowStock" placeholder="" size="normal" clearable />
                  </template>
                </el-table-column>
                <el-table-column
                  prop="id"
                  label="sku编码"
                >
                  <template v-slot="scope">
                    <el-input v-model="scope.row.skuCode" placeholder="" size="normal" clearable />
                  </template>
                </el-table-column>
                <el-table-column
                  prop="id"
                  label="价格"
                >
                  <template v-slot="scope">
                    <el-input v-model="scope.row.price" placeholder="" size="normal" clearable />
                  </template>
                </el-table-column>
                <el-table-column
                  prop="id"
                  label="销量"
                >
                  <template v-slot="scope">
                    <el-input v-model="scope.row.sale" placeholder="" size="normal" clearable />
                  </template>
                </el-table-column>

                <el-table-column label="操作" align="center" fixed="right" width="200">
                  <template slot-scope="scope">
                    <el-button style="color:red;" size="mini" type="text" @click="del(scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-row>
        </div>
        <div v-show="step==3">
          <p>详情描述</p>
          <el-divider />
          <el-row :gutter="20">
            <el-col :span="2" :offset="0">
              商品详情
            </el-col>
            <el-col :span="22" :offset="0">
              <Tinymce v-model="form.product.detailDesc" />
              <!-- <mavon-editor v-if="article.editorType == 1" ref="mdEdit" @imgAdd="$imgAdd" /> -->
            </el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top:20px">
            <el-col :span="2" :offset="0">
              备注
            </el-col>
            <el-col :span="17" :offset="0">
              <el-input
                v-model="form.product.note"
                type="textarea"
                :rows="2"
                placeholder="备注"
              />
            </el-col>
          </el-row>
        </div>
        <el-row :gutter="20">
          <el-col :span="8" :offset="8">
            <el-form-item style="margin-top:30px">
              <el-button v-if="step!=1" @click="goPreStep">返回上一步</el-button>
              <el-button v-if="step!=3" type="primary" @click="goNextStep">下一步,填写{{ step==1?'库存信息':'移动端详情' }}</el-button>
              <el-button v-if="step==3" type="primary" @click="save">提交保存</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import { getAllCategory } from '@/api/product/category'
import { findAllBrand, productSkusDetail, addProductAndSkus, updateProductAndSkus, removeOssFile } from '@/api/product/list'
import mix from '@/mixins'
import _ from 'lodash'
export default {
  name: 'AddGoods',
  components: {
    Tinymce
  },
  mixins: [mix],
  data() {
    return {
      color: '',
      colorList: [
        {
          name: '黑色',
          isSelected: false
        },
        {
          name: '红色',
          isSelected: false
        }
      ],
      size: '',
      sizeList: [
        {
          name: '128g',
          isSelected: false
        },
        {
          name: '256g',
          isSelected: false
        }
      ],
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      step: 1,
      // goods: {
      //   serviceIds: [],
      //   albumPics: [],
      //   pic: ''
      // },
      categoryList: [],
      brandList: [],
      fileList: [],
      // serviceIdsArr: [],
      form: {
        // pmsSkuStockList 商品sku部分
        'pmsSkuStockList': [

        ],
        // product 商品基本信息
        'product': {
          'albumPics': [],
          'brandId': '',
          'brandName': '',
          'createTime': '',
          'deleteStatus': '',
          'description': '',
          'detailDesc': '',
          'detailHtml': '',
          'detailMobileHtml': '',
          'detailTitle': '',
          'feightTemplateId': '',
          'giftGrowth': '',
          'giftPoint': '',
          'id': '',
          'keywords': '',
          'lowStock': '',
          'modifyTime': '',
          'name': '',
          'newStatus': '',
          'note': '',
          'originalPrice': '',
          'pic': '',
          'previewStatus': '',
          'price': '',
          'productAttributeCategoryId': '',
          'productCategoryId': '',
          'productCategoryName': '',
          'productSn': '',
          'promotionEndTime': '',
          'promotionPerLimit': '',
          'promotionPrice': '',
          'promotionStartTime': '',
          'promotionType': '',
          'publishStatus': '',
          'recommendStatus': '',
          'sale': '',
          'serviceIds': [],
          'sort': '',
          'stock': '',
          'subTitle': '',
          'unit': '',
          'usePointLimit': '',
          'verifyStatus': '',
          'weight': ''
        }
      }
    }
  },

  created() {
    // console.log(this.$route.query.id)
    this.getCategory()
    this.getBrandList()
    this.getProduct()
  },

  mounted() {

  },

  methods: {
    save() {
      this.form.product.serviceIds = this.form.product.serviceIds.join(',')
      this.form.product.albumPics = this.form.product.albumPics.join(',')
      var deep = _.cloneDeep(this.form)
      deep.pmsSkuStockList.forEach(ele => {
        ele.spData = JSON.stringify(ele.spData)
      })
      if (this.$route.params.id) {
        updateProductAndSkus(deep)
          .then(res => {
            // console.log(res)
            this.$router.push('/product/list')
          })
        return
      }
      addProductAndSkus(deep)
        .then(res => {
          // console.log(res)
          this.$router.push('/product/list')
        })
    },
    // 删除
    del(index) {
      this.form.pmsSkuStockList.splice(index, 1)
    },
    // 新增sku
    addSku() {
      var obj = {
        'createTime': '',
        'id': '',
        'lockStock': '',
        'lowStock': '',
        'modifyTime': '',
        'pic': '',
        'price': '',
        'productId': '',
        'promotionPrice': '',
        'sale': '',
        'skuCode': '',
        'spData': [{ 'key': '颜色', value: '' }, { 'key': '大小', value: '' }],
        'stock': ''
      }
      this.form.pmsSkuStockList.push(obj)
    },
    // 上传sku图片
    getUploadImg(e, index) {
      // console.log(e)
      this.form.pmsSkuStockList[index].pic = e
    },
    // 生成sku列表
    sku() {
      var colorList = this.colorList.filter(ele => ele.isSelected)
      var sizeList = this.sizeList.filter(ele => ele.isSelected)
      colorList.forEach(ele => {
        sizeList.forEach(ite => {
          var data = [{ 'key': '颜色', value: ele.name }, { 'key': '大小', value: ite.name }]
          var obj = {
            'createTime': '',
            'id': '',
            'lockStock': '',
            'lowStock': '',
            'modifyTime': '',
            'pic': '',
            'price': '',
            'productId': '',
            'promotionPrice': '',
            'sale': '',
            'skuCode': '',
            'spData': data,
            'stock': ''
          }
          this.form.pmsSkuStockList.push(obj)
        })
      })
    },
    addSize() {
      if (this.size.length === 0) {
        return
      }
      if (this.sizeList.find(ele => ele.name === this.size)) {
        return
      }
      var obj = {
        name: this.size,
        isSelected: false
      }
      this.sizeList.push(obj)
      this.size = ''
    },
    addColor() {
      if (this.color.length === 0) {
        return
      }
      if (this.colorList.find(ele => ele.name === this.color)) {
        return
      }
      var obj = {
        name: this.color,
        isSelected: false
      }
      this.colorList.push(obj)
      this.color = ''
    },
    delSize(index) {
      this.sizeList.splice(index, 1)
    },
    delColor(index) {
      this.colorList.splice(index, 1)
    },
    getBrandName(e) {
      this.form.product.brandName = this.brandList.find(ele => ele.id === e).name
    },
    getCategoryName(e) {
      this.form.product.productCategoryName = this.categoryList.find(ele => ele.id === e).name
    },
    getProduct() {
      if (this.$route.params.id) {
        productSkusDetail(this.$route.params.id)
          .then(res => {
            console.log(res)
            if (res.data.product) {
              this.form.product = res.data.product
              this.form.product.serviceIds = res.data.product.serviceIds.split(',')
              this.form.product.albumPics = res.data.product.albumPics.split(',')

              this.form.product.albumPics.forEach(ele => {
                this.fileList.push({
                  'url': ele
                })
              })
              res.data.skus.forEach(ele => {
                ele.spData = JSON.parse(ele.spData)
              })
              this.form.pmsSkuStockList = res.data.skus
            }
          })
      }
    },
    // 画册上传成功
    uptAlbumPics(response) {
      if (response.success) {
        // this.albumPicsArr.push(response.data.fileUrl)
        // this.form.product.albumPics = this.albumPicsArr.join(',')
        this.form.product.albumPics.push(response.data.fileUrl)
        // 清空已上传的文件列表
        this.$refs.clearUpload.clearFiles()
      } else {
        this.$message.error(response.message)
      }
    },
    handleRemove(file, fileList) {
      console.log(file.url.substr(file.url.indexOf('bftec')))
      console.log(file, fileList)
      const formData = new FormData()
      formData.append('fileName', file.url.substr(file.url.indexOf('bftec')))
      removeOssFile(formData)
        .then(res => {
          console.log(res)
          const index = this.fileList.findIndex(item => item.uid === file.uid)
          this.fileList.splice(index, 1)// 移除已上传的图片
          this.form.product.albumPics.splice(index, 1)
        })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleDownload(file) {
      console.log(file)
    },
    // 图片上传之前校验
    beforeCoverImgUpload(file) {
      // const isJPG = file.type === 'image/jpeg' | file.type === 'image/png' | file.type === 'image/gif' | file.type === 'image/webp'
      const reg = /^image\/(jpeg|png|gif|webp)$/
      const isImg = reg.test(file.type)
      const isLt1dot5M = file.size / 1024 / 1024 < 1.5

      if (!isImg) {
        this.$message.error('上传图片只能是 jpeg|png|gif|webp 格式!')
      }
      if (!isLt1dot5M) {
        this.$message.error('上传图片大小不能超过 1.5MB!')
      }
      return isImg && isLt1dot5M
    },
    // 图片上传成功
    coverImgUploadSucc(response) {
      // console.log(response)
      if (response.success) {
        this.form.product.pic = response.data.fileUrl
        // 清空已上传的文件列表
        this.$refs.clearUpload.clearFiles()
      } else {
        this.$message.error(response.message)
      }
    },
    // 上一步
    goPreStep() {
      this.step--
    },
    // 下一步
    goNextStep() {
      this.step++
    },
    // 获取分类数据
    getCategory() {
      getAllCategory()
        .then(res => {
          // console.log(res)
          const leju = res.data.items.find(ele => ele.category.name === '乐居')
          if (leju) {
            this.categoryList = leju.children
          }
          // this.categoryList = res.data.items
        })
    },
    // 获取品牌数据
    getBrandList() {
      findAllBrand()
        .then(res => {
          // console.log(res)
          this.brandList = res.data.items
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.stepList{
  .steps{
    background-color: #fff;
    padding: 50px 250px;

  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
